package cn.iocoder.yudao.module.mqtt.service.deviceauth;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.mqtt.controller.admin.deviceauth.vo.*;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.deviceauth.DeviceAuthDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.mqtt.dal.mysql.deviceauth.DeviceAuthMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.mqtt.enums.ErrorCodeConstants.*;

/**
 * 设备报警授权 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class DeviceAuthServiceImpl implements DeviceAuthService {

    @Resource
    private DeviceAuthMapper deviceAuthMapper;

    @Override
    public Long createDeviceAuth(DeviceAuthSaveReqVO createReqVO) {
        // 插入
        DeviceAuthDO deviceAuth = BeanUtils.toBean(createReqVO, DeviceAuthDO.class);
        deviceAuthMapper.insert(deviceAuth);
        // 返回
        return deviceAuth.getId();
    }

    @Override
    public void updateDeviceAuth(DeviceAuthSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceAuthExists(updateReqVO.getId());
        // 更新
        DeviceAuthDO updateObj = BeanUtils.toBean(updateReqVO, DeviceAuthDO.class);
        deviceAuthMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceAuth(Long id) {
        // 校验存在
        validateDeviceAuthExists(id);
        // 删除
        deviceAuthMapper.deleteById(id);
    }

    @Override
        public void deleteDeviceAuthListByIds(List<Long> ids) {
        // 校验存在
        validateDeviceAuthExists(ids);
        // 删除
        deviceAuthMapper.deleteByIds(ids);
        }

    private void validateDeviceAuthExists(List<Long> ids) {
        List<DeviceAuthDO> list = deviceAuthMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_AUTH_NOT_EXISTS);
        }
    }

    private void validateDeviceAuthExists(Long id) {
        if (deviceAuthMapper.selectById(id) == null) {
            throw exception(DEVICE_AUTH_NOT_EXISTS);
        }
    }

    @Override
    public DeviceAuthDO getDeviceAuth(Long id) {
        return deviceAuthMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceAuthDO> getDeviceAuthPage(DeviceAuthPageReqVO pageReqVO) {
        return deviceAuthMapper.selectPage(pageReqVO);
    }

}